package codingforgreat.lchot150;

public class Lc230 {
    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }

        public int kthSmallest(TreeNode root, int k) {
            int path = 0;
            TreeNode cur = root;
            TreeNode MR = null;
            while (cur != null) {
                MR = cur.left;
                if (MR != null) {
                    while (MR.right != null && MR.right != cur) {
                        MR = MR.right;
                    }
                    if (MR.right == cur) {
                        path++;
                        if (path == k) {
                            return cur.val;
                        }
                        MR.right = null;
                    } else {
                        MR.right = cur;
                        cur = cur.left;
                        continue;
                    }
                } else {
                    path++;
                    if (path == k) {
                        return cur.val;
                    }
                }
                cur = cur.right;
            }
            return 0;
        }
    }
}
